package com.lwisniewski.pg.pulsehematometry.serial.main;

import gnu.io.CommPortIdentifier;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.log4j.Logger;

import com.lwisniewski.pg.pulsehematometry.serial.facade.SerialPortReaderFacade;
import com.pulsehematometry.serial.setup.SerialPortReaderSetup;

public class SerialPortReaderService implements SerialPortReaderFacade {

	private final static Logger LOGGER = Logger
			.getLogger(SerialPortReaderService.class);

	private static SerialPortReaderSetup serialPortReaderSetup;
	private InputStream inputStream;

	public SerialPortReaderService() {
		serialPortReaderSetup = SerialPortReaderSetup.getInstance();
	}

	public InputStream getRs232InputStream() {
		try {
			inputStream = serialPortReaderSetup.getRs232InputStream();
		} catch(IOException e) {
			LOGGER.error("Exception was thrown when retrieving active port identifier." + e.getMessage());
		}
		
		return inputStream;
	}

	public CommPortIdentifier getActiveCommPortIdentifier() {
		CommPortIdentifier commPortId = null;

		try {
			commPortId = serialPortReaderSetup.getUsedCommPortIdentifier();
		} catch (Exception e) {
			LOGGER.error("Exception was thrown when retrieving active port identifier."
					+ e.getMessage());
		}

		return commPortId;
	}

	public void openPort(CommPortIdentifier id) {
		serialPortReaderSetup.openPort(id);

	}

	public void closePort(CommPortIdentifier id) {
		serialPortReaderSetup.closePort(id);
	}

	public List<CommPortIdentifier> getAvailablePortList() {
		return serialPortReaderSetup.getAvailableSerialPortList();
	}

}
